package ru.gelin.android.bells.timers;

import java.util.Comparator;
import java.util.Date;

/**
 *  Order timers by the alarm time.
 *  Because of the alarm time depends on the current time 
 *  (can be equal to the start time when the start time is in the future),
 *  the constructor of this comparator takes the current time as argument.
 */
class TimerComparator implements Comparator<Timer> {

    /** Current time to compare */
    Date now = new Date();
    
    /**
     *  Creates new comparator for the current time.
     *  @param  current time
     */
    TimerComparator(Date now) {
        this.now = now;
    }
    
    /**
     *  Order timers by alarm time and ID.
     *  If IDs of both timers are equal, timers are considered equal too.
     */
    @Override
    public int compare(Timer timer1, Timer timer2) {
        if (timer1.id > 0 && timer1.id == timer2.id) {
            return 0;   //equals by ID
        }
        Date alarm1 = timer1.getAlarmTime(now);
        Date alarm2 = timer2.getAlarmTime(now);
        int alarmCompare = alarm1.compareTo(alarm2);
        if (alarmCompare != 0) {
            return alarmCompare;
        }
        //ordering by ID
        return timer1.id - timer2.id;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((now == null) ? 0 : now.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        TimerComparator other = (TimerComparator) obj;
        if (now == null) {
            if (other.now != null)
                return false;
        } else if (!now.equals(other.now))
            return false;
        return true;
    }

}
